# -*- coding: utf-8 -*-
"""
Created on Sat Aug 18 13:29:06 2018

@author: Who

柚子财经
http://www.wjunkj.com/

"""

import requests
import re
import json
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url, data):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.post(url, timeout=30, data=data, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_Zx(url, data):
    text = get_html_text(url, data)
    if not text:
        return None
    text = json.loads(text)['postlist']
    regex = re.compile(r'> (\d{4}-\d{2}-\d{2}) \d{2}:\d{2}:\d{2}<')
    dates = re.findall(regex, text)
    return dates


def count_process_Zx():  # 快讯

    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 0
    while 1:
        data = {
            'total': '49',
            'action': 'fa_load_postlist',
            'paged': a,
            'home': 'true',
            'wowDelay': '0.3s'
        }
        url = 'http://www.wjunkj.com/wp-admin/admin-ajax.php'
        dates = get_dates_Zx(url, data)
        if not dates:
            break
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        print('----柚子财经最新第{}页获取中----'.format(a))
        if d4 > 0:
            break
    return (d1, d2, d3)


def count_process_Kx():  # 快讯

    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 0
    while 1:
        data = {
            'total': '51',
            'action': 'fa_load_postlist',
            'paged': a,
            'category': '1',
            'wowDelay': '0.3s'
        }
        url = 'http://www.wjunkj.com/wp-admin/admin-ajax.php'
        dates = get_dates_Zx(url, data)
        if not dates:
            break
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        print('----柚子财经快讯第{}页获取中----'.format(a))
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '柚子财经'
    t1 = count_process_Kx()
    t2 = count_process_Zx()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0] + t2[0], "yesterday": t1[1] + t2[1], "frontday": t1[2] + t2[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
